package com.OrderingServer.Controller.common;

import cn.hutool.core.io.FileUtil;
import com.OrderingServer.config.QiNiuYunConfig;
import com.OrderingServer.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
import java.io.*;


@RestController
@RequestMapping("files")
@Slf4j
public class FileController {

 @Autowired
    QiNiuYunConfig qiNiuYunConfig;

    //  D:/test-code/baiyexing-server
    private static final String ROOT_PATH = System.getProperty("user.dir") + "/files";

    /**
     * 上传图片
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取到原始的文件名   aaa.png   aaa.png

        String flag = UUID.randomUUID().toString();
        String fileName = flag + "." + originalFilename.split("\\.")[1];    //  asdasdwrwerwerwert45645645645.png

//        File finalFile = new File(ROOT_PATH + "/" + fileName);  // 最终存到磁盘的文件对象
//        if (!finalFile.getParentFile().exists()) {  // 如果父级目录不存在 就得创建
//            finalFile.getParentFile().mkdirs();
//        }
//        file.transferTo(finalFile);
        // 返回文件的url
        String url = qiNiuYunConfig.uploadImgToQiNiu(file.getInputStream(),fileName);
        log.info("服务器文件上传成功:"+url);
        return Result.success(url);
    }

//    /**
//     * 图片预览
//     * @param fileName
//     * @param response
//     * @throws IOException
//     */
//    @GetMapping("/download")
//    public void download(@RequestParam("file") String fileName, HttpServletResponse response) throws IOException {
//        File file = new File(ROOT_PATH + "/" + fileName);  // 文件在存盘存储的对象
//        ServletOutputStream os = response.getOutputStream();
//        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        response.setContentType("application/octet-stream");
//        // os.write(FileUtil.readBytes(file));
//        byte[] byteps=new byte[1024*10];
//        FileUtil.writeToStream(file, os);
//        os.flush();
//        os.close();
//    }
}
